#!/usr/bin/env python
# -*- coding:utf-8 -*-
import binascii
import os
from libs import printer

def check_path(fp):
    if os.path.isfile(fp):
        return True
    else:
        return False

def get_file_size(fp):
    return os.path.getsize(fp)

def read_file(fp,size):
    with open(fp,'rb') as fr:
        c = fr.read(size)
        if c:
            ls = [c[i:i+1] for i in range(len(c))]
            for i in range(len(ls)):
                yield ls[i]
def check_ascii(ct):
    result = []
    for c in range(len(ct)):
        t = ct[c:c+1]
        if ord(t)<127 and ord(t)>=32:
            result.append(True)
        else:
            result.append(False)
    return all(result)

def vali_char(b):
    if check_ascii(b):
        return b
    else:
        return b'.'

def execute(fp):
    try:
        content = b""
        memAddr = 0
        fp = input("请输入文件路径: ")
        cfp = check_path(fp)
        if cfp:
            fsize = get_file_size(fp)
            printer.info("当前文件大小: " + str(fsize) + " 字节")
            size = input("请输入要读取的字节数: ")
            size = int(size)
            for b in read_file(fp,size):
                content = content + vali_char(b)
                if memAddr%16 == 0:
                    print(format(memAddr,"06X"),end="" )
                    print("   ",end="")
                    print(binascii.hexlify(b).decode(encoding='utf-8', errors='strict'),end="")
                    print(" ",end="")
                elif memAddr%16 == 15:
                    print(binascii.hexlify(b).decode(encoding='utf-8', errors='strict'),end="")
                    print("   ",end="")
                    print(content.decode(encoding='utf-8', errors='strict'),end="")
                    content = b""
                    print("")
                else:
                    print(binascii.hexlify(b).decode(encoding='utf-8', errors='strict'),end="")
                    print(" ",end="")
                memAddr += 1
        print("")
    except Exception as e:
        printer.warn("运行出现异常!")